<?php

/**
 * 培训控制器
 * @author yanghao <yh38615890@sina.cn>
 * @date 07-04-12
 * @copyright (c) gandianli
 */

namespace app\api\controller;

use app\api\Base;
use think\Config;
use think\Db;
use think\exception\HttpException;
use think\Session;
use com\gdl\newagk\dataobject\adminpaper\AdminPaperRequestDTO;
use com\gdl\newagk\dataobject\adminpaper\AdminpaperDTO;
use com\gdl\newagk\interfaces\AdminpaperServiceClient;

class AdminPaper extends Base
{
	public function index(){
	}
	//添加试卷
	public function add(){

			/*$code = $this->request->post('code') ? $this->request->post('code') : '';
				// 提交
				if (empty($username) || empty($password) || empty($code)) {
					$data = ['msg'=>'缺少必要参数','code'=>'400','data'=>[]];
					return json_encode($data);
				}*/

				$datas = $this->request->post();
				
				
				if (empty($datas)) {
					$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
					return json_encode($data);
				}
				
				/***测试数据***/
			/*	$datas['title']='2019变电考试试卷一套';
				$datas['qbankid']=208; //题库
				$datas['total_time']=60;
				$datas['total_score']=100;
				$datas['pass_score']=60;
				$datas['typesof']=1;
				$datas['problemet']=1;
				$datas['ratio']=[['1'=>1,'2'=>2,'3'=>'3']];
				$datas['status']=1;
				$datas['shared']=1;
				$datas['userid']=1;
				////////////////////
				
				$datas = [
				'pass_score'=>60,//及格分数
				'problemet'=>1,	//2普通试卷【固定抽题】，1随机生成试卷【随机抽题】
				'qbankid'=>208,		//number	题库id
				'ratio'=>[[0=> 1, 1=>"", 2=> 30, 3=>1, 4=> "1", 5=>"22"]],
				'shared'=>1,		//number	'0是不共享1是共享
				'status'=>1,		//number	1正常可用【启用】，2不可用【禁用】,3平台禁用
				'title'=>'测试',
				'total_score'=>100,		//number	试卷总分
				'total_time'=>60,	//number	考试时长
				'typesof'=>3,		//number	1模拟练习，2正式考试 ,3公用
				'userid'=>1,//	number	当前用户id,
				
						];
				
				*/
				/****测试数据 end***/
				$filename['name'] = getStr($datas['title'], 'string');
				$filename['dbs'] = getStr($datas['qbankid'], 'int'); //题库
				$duration = getStr($datas['total_time'], 'int');
				$filename['duration'] = $duration*60;
				$filename['totalScore'] = getStr($datas['total_score'], 'int');
				$filename['passScore'] = getStr($datas['pass_score'], 'int');
				$filename['puse'] = getStr($datas['typesof'], 'int');
				$filename['paperType'] = getStr($datas['problemet'], 'int');
				$filename['settings'] =json_encode($datas['ratio']);
				$filename['status'] = getStr($datas['status'], 'int');
				$filename['shared'] = getStr($datas['shared'], 'int');
				$filename['userid'] = getStr($datas['userid'], 'int');
				
				if (empty($filename['name']) || empty($filename['settings'])) {
					$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
					return json_encode($data);
				}
				if(!empty($datas['labelId'])){
					//同步为唐川的那种格式方便前端传值
					$labelId =explode(',',$datas['labelId']);
					$labelId_value=explode(',',$datas['labelId_value']);
					$labelIds = [];
					for($i=0;$i<count($labelId);$i++){
						$labelIds[] = $labelId[$i].'_'.$labelId_value[$i];
					}
					if(!empty($labelIds)){
						$filename['labelId'] = implode(',',$labelIds);
					}
				}
				try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AdminpaperServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AdminpaperRequestDTO();
				$engprojectDo->filename = $filename;
				$result = $api->add($engprojectDo);

				if($result->code){
					$data = ['msg'=>'成功','code'=>'200','data'=>[]];
				} else {
					$data = ['msg'=>$result->message,'code'=>'400','data'=>[]];
				}
			} catch (Exception $ex) {
				$data = ['msg'=>'失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);

	}
	
	//修改试卷
	public function edit(){

			/*$code = $this->request->post('code') ? $this->request->post('code') : '';
				// 提交
				if (empty($username) || empty($password) || empty($code)) {
					$data = ['msg'=>'缺少必要参数','code'=>'400','data'=>[]];
					return json_encode($data);
				}*/

				$datas = $this->request->post();
				/*$datas['id']='4';
$datas['labelId']='';
$datas['labelId_value']='';
$datas['title']='123';
$datas['qbankid']='4';
$datas['total_time']='60';
$datas['total_score']='100';
$datas['pass_score']='60';
$datas['problemet']='1';
$datas['status']='1';
$datas['shared']='0';
$datas['typesof']='1';
$datas['totalNum']='1';
$datas['ratio'][0][0]='1';
$datas['ratio'][0][1]='0';
$datas['ratio'][0][2]='0';
$datas['ratio'][0][3]='1';
$datas['ratio'][0][4]='100';
$datas['ratio'][0][5]='4';
*/
				if (empty($datas)) {
					$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
					return json_encode($data);
				}
				
				/***测试数据***/
			/*	$datas['title']='2019变电考试试卷一套';
				$datas['qbankid']=208; //题库
				$datas['total_time']=60;
				$datas['total_score']=100;
				$datas['pass_score']=60;
				$datas['typesof']=1;
				$datas['problemet']=1;
				$datas['ratio']=[['1'=>1,'2'=>2,'3'=>'3']];
				$datas['status']=1;
				$datas['shared']=1;
				$datas['userid']=1;
				//////////
				$datas = [
				'id'=>6,
				'pass_score'=>50,//及格分数
				'problemet'=>2,	//2普通试卷【固定抽题】，1随机生成试卷【随机抽题】
				'qbankid'=>208,		//number	题库id
				'ratio'=>[[1,1,148,4,2]],
				'shared'=>0,		//number	'0是不共享1是共享
				'status'=>0,		//number	1正常可用【启用】，2不可用【禁用】,3平台禁用
				'title'=>'测试2222222',
				'total_score'=>90,		//number	试卷总分
				'total_time'=>70,	//number	考试时长
				'typesof'=>2,		//number	1模拟练习，2正式考试 ,3公用
				'userid'=>1,//	number	当前用户id,
				
						];
				*/
				
				/****测试数据 end***/

				$filename['name'] = getStr($datas['title'], 'string');
				$filename['dbs'] = getStr($datas['qbankid'], 'int'); //题库
				$duration = getStr($datas['total_time'], 'int');
				$filename['duration'] = $duration*60;
				$filename['totalScore'] = getStr($datas['total_score'], 'int');
				$filename['passScore'] = getStr($datas['pass_score'], 'int');
				$filename['puse'] = getStr($datas['typesof'], 'int');
				$filename['paperType'] = getStr($datas['problemet'], 'int');
				$filename['settings'] =json_encode($datas['ratio']);
				$filename['status'] = getStr($datas['status'], 'int');
				$filename['shared'] = getStr($datas['shared'], 'int');
				$filename['userid'] = getStr($datas['userid'], 'int');
				$filename['admin_reg'] = 1;
				if(!empty($datas['labelId'])){
					//同步为唐川的那种格式方便前端传值
					$labelId =explode(',',$datas['labelId']);
					$labelId_value=explode(',',$datas['labelId_value']);
					$labelIds = [];
					for($i=0;$i<count($labelId);$i++){
						$labelIds[] = $labelId[$i].'_'.$labelId_value[$i];
					}
					if(!empty($labelIds)){
						$filename['labelId'] = implode(',',$labelIds);
					}
				}
				$filename['id'] = getStr($datas['id'], 'int');
				try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AdminpaperServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AdminpaperRequestDTO();
				$engprojectDo->filename = $filename;
				$result = $api->edit($engprojectDo);

				if($result->code){
					$data = ['msg'=>'成功','code'=>'200','data'=>[]];
				} else {
					$data = ['msg'=>$result->message,'code'=>'400','data'=>[]];
				}
			} catch (Exception $ex) {
				$data = ['msg'=>'失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);

	}
	
	
	//试卷列表
	public function paperList(){

		$plaform_id = $this->request->param('plaform_id') ? $this->request->param('plaform_id/d') : '1';
		$page = $this->request->param('page')>1 ? $this->request->param('page/d') : 1;
		$pagesize = $this->request->param('pagesize')>0 ? $this->request->param('pagesize/d') : 10;
		$title = $this->request->param('title') ? getStr($this->request->param('title'), 'string') : '';
		$status = $this->request->param('status') ? getStr($this->request->param('status'), 'string') : '';
		
		$filename['qid'] = $this->request->param('qid') ? $this->request->param('qid/d') : 0;
		$filename['typesof'] = $this->request->param('typesof') ? $this->request->param('typesof/d') : 0;
		$filename['problemet'] = $this->request->param('problemet') ? getStr($this->request->param('problemet'), 'string') : '';//fixed 固定 randoms 随机
		$filename['shared'] = $this->request->param('shared') ? getStr($this->request->param('shared'), 'string') : '';
		$filename['plaform'] = $this->request->param('plaform') ? getStr($this->request->param('plaform'), 'string') : '';
		$filename['del'] = $this->request->param('del')=='recycling' ? 1 : 0;
		$filename['spec'] = $this->request->param('spec') ? 1 : 0;
		if($plaform_id=='a'){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}
		
		$filename['title'] = $title;
		$filename['status'] = $status;
		$filename['page'] = $page;
		$filename['pagesize'] = $pagesize;
		$plaform_id = (int)$plaform_id;

				
				try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AdminpaperServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AdminpaperRequestDTO();
				$engprojectDo->filename = $filename;
				$result = $api->paperlist($engprojectDo);

				if($result->code){
					if(empty($result->data)){
						$data = ['msg'=>'成功','code'=>'200','data'=>[],'totalNumber'=>0];
					} else {
						
					
					$data = ['msg'=>'成功','code'=>'200','data'=>$result->data,'totalNumber'=>$result->message];
					}
				} else {
					$data = ['msg'=>'失败','code'=>'400','data'=>[],'totalNumber'=>0];
				}
			} catch (Exception $ex) {
				$data = ['msg'=>'失败','code'=>'400','data'=>[]];
			}

			return json_encode($data);

	}
	
	//查看试卷配置
	public function lookOver(){
		$plaform_id = $this->request->param('plaformid') ? $this->request->param('plaformid/d') : '1';

		$id = $this->request->param('id') ? $this->request->param('id/d') : 0;
		if($plaform_id=='a' || !$id){
			
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		
		}
				try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AdminpaperServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AdminpaperDTO();
				$engprojectDo->plaform_id = $plaform_id;
				$engprojectDo->id = $id;
				$result = $api->lookOver($engprojectDo);
		

				$questioNum=0;
				$score=0;
				if($result->code){
					//$result->data[0]['ratio'] = unserialize($result->data[0]['ratio']);
					
					$ratio = unserialize($result->data[0]['ratio']);

					$result->data[0]['ratio'] = $ratio;
					$result->data[0]['id'] =$id;

					$result->data[0]['labelId'] = json_decode($result->data[0]['labelId'],true);
					if(empty($result->data[0]['labelId'])){
						$result->data[0]['labelId']=['tag'=>[],'tagSelect'=>[]];
					}
					$data = ['msg'=>'成功','code'=>'200','data'=>$result->data[0]];
		
				} else {
					$data = ['msg'=>$result->message,'code'=>'400','data'=>[]];
				}
			} catch (Exception $ex) {
				$data = ['msg'=>'失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);
	}
	
	
	//查看试卷
	public function lookPaper(){
		$plaform_id = $this->request->param('plaform_id') ? $this->request->param('plaform_id/d') : '1';
		$id = $this->request->param('id') ? $this->request->param('id/d') : 0;
		if($plaform_id=='a' || !$id){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}

				try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AdminpaperServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AdminpaperDTO();
				$engprojectDo->plaform_id = $plaform_id;
				$engprojectDo->id = $id;
				$result = $api->lookPaper($engprojectDo);
				
				$data = json_decode($result->message,true);
				
			} catch (Exception $ex) {
				$data = ['list'=>[],'count'=>0,'qbankName'=>'','duration'=>'','totalScore'=>'','passScore'=>'','paperName'=>''];
			}

			/*********************/
				vendor("TCPDF.tcpdf");
				$tpickeys = array();
				$keys = array();
				$num=[
						'一',
						'二',
						'三',
						'四',
						'五',
						'六',
					];
			//	$ques_type = ['1'=>'单选题','2'=>'多选题','3'=>'判断题','4'=>'填空题','5'=>'问答题'];
				$ques_type =  ['single'=>'单选题','more'=>'多选题','judge'=>'判断题','gapFilling'=>'填空题','subjectivity'=>'问答题'];
				

				$pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
				$pdf->SetCreator(PDF_CREATOR);
				$pdf->SetAuthor('Nicola Asuni');
				$pdf->SetTitle($data['paperName']);
				$pdf->SetSubject('TCPDF Tutorial');
				$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
				// 设置页眉和页脚信息 
				$txt = $data['paperName'];
				$pdf->SetHeaderData(false, 20, false, $txt,array(0,64,255), array(0,64,128)); //第一个参数是放log的
				// 设置页眉和页脚字体 
				$pdf->setHeaderFont(Array('stsongstdlight', '', '10')); 

			// ---------------------------------------------------------

			//Close and output PDF document
			// remove default header/footer
				$pdf->setPrintHeader(true);
				$pdf->setPrintFooter(false);

				// set default monospaced font
				$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

				// set margins
				$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

				// set auto page breaks
				$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

				// set image scale factor
				$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

				// set some language-dependent strings (optional)
				if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
					require_once(dirname(__FILE__).'/lang/eng.php');
					$pdf->setLanguageArray($l);
				}

				$pdf->SetFont('times', 'BI', 10);
				$pdf->AddPage();
				$pdf->SetFont('stsongstdlight', '', 14);
				$txt = $data['paperName'];
				$pdf->Write(0, $txt, '', 0, 'C', true, 0, false, false, 0);
				$ic=0;
				$pdf->SetFont('stsongstdlight', '', 10);
				$html = '
				<table border="0">
					<tr>
						<th>来源题库：'.$data['qbankName'].'</th>
						
						<th align="right">考试时长：'.($data['duration']/60).'</th>
					</tr>
					<tr>
						<th>试题数目：'.$data['count'].'</th>
						
						<th align="right">及格分数：'.$data['passScore'].'</th>
					</tr>
					
				</table>';
				$nums = [];
				
				$html .= '<table border="1"><tr align="center">';

					foreach($data['list'] as $kl=>$vl){
						$nums[] = count($vl);
						$html .= '<th>'.$ques_type[$kl].'</th>';
					}
				
					$html .= '<th>总分</th>
					</tr>
					<tr align="center">';
					foreach($nums as $vn){
							$html .= '<td>'.$vn.'</td>';
					}
					
					$html .= '<td>'.$data['totalScore'].'</td></tr></table>';
				$pdf->writeHTML($html, true, false, true, false, '');
				foreach($data['list'] as $ko=>$vo){
					$pdf->SetFont('stsongstdlight', '', 12);
					$txt = $num[$ic].'、'.$ques_type[$ko];	
					$pdf->Write(0, $txt, '', 0, 'L', true, 0, false, false, 0);
					
					$txt = '';
					$pdf->SetFont('stsongstdlight', '', 10);
					$i=1;
					
					foreach($vo as $kl=>$vl){
					$selectAnw = str_replace(array("\r\n","\n",'\r'),"  ",$vl["select"]);
					if($selectAnw=='暂无选项'){
						$selectAnw='';
					}
					$txt .= $i.'、'.$vl["question"]."\r\n".$selectAnw."\r\n\r\n";//."\r\n正确答案：".$vl["q_answer"]
					$i++;
					}
					//$txt = htmlspecialchars_decode($txt);
					$txt = str_replace(array('&lt;p&gt;','&lt;/p&gt;','#*#'),' ',$txt);//处理掉p 标签
					$pdf->Write(0, $txt, '', 0, 'L', true, 0, false, false, 0);
					$ic++;
				}
				$pdf->Output('kaoshi.pdf', 'I');
				exit;

	}
	
	/**
     * 下载试卷
     * @return mixed
     */
    public function download()
    {
		
		$plaform_id = $this->request->param('plaform_id') ? $this->request->param('plaform_id/d') : '1';
		$id = $this->request->param('id/d') ? $this->request->param('id') : 0;
		if($plaform_id=='a' || !$id){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}

				try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AdminpaperServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AdminpaperDTO();
				$engprojectDo->plaform_id = $plaform_id;
				$engprojectDo->id = $id;
				$result = $api->lookPaper($engprojectDo);

				$data = json_decode($result->message,true);
			} catch (Exception $ex) {
				header("HTTP/1.1 404 Not Found");
				exit;
			}

			$num=[
						'single'=>'一',
						'more'=>'二',
						'judge'=>'三',
						'gapFilling'=>'四',
						'subjectivity'=>'五',
						//'六',
					];
				$ques_type = ['single'=>'单选题','more'=>'多选题','judge'=>'判断题','gapFilling'=>'填空题','subjectivity'=>'问答题'];
	
			echo '  
				<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">  
				<head>  
				<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>  
				<xml><w:WordDocument><w:View>Print</w:View></xml>  
				</head>';  
			echo '<body>
			<table width="100%" border="0" cellspacing="0" cellpadding="0">
			  <tr>
				<td align="center"><h2>'.$data['paperName'].'</h2></td>
			  </tr>';
			  foreach($data['list'] as $k=>$v){
				 
				  echo '<tr>
						 <td><span style="font-size: 18px">'.$num[$k].'、'.$ques_type[$k].'</span></td>
					    </tr>';
				foreach($v as $kc=>$val){
					$selectAnw = strFilter($val["select"]);
					if($selectAnw=='暂无选项'){
						$selectAnw='';
					}
					 echo '<tr>
						<td style="padding-left:14px"><br>'.($kc+1).'、'.$val['question'].'</td>
					  </tr>
					  <tr>
						<td style="padding-left:14px">'.$selectAnw.'</td>
					  </tr>';
				}
			  }
			echo '</table></body>';
			$paperName = empty($data['paperName']) ? 'test' : urlencode($data['paperName']);
			ob_start(); //打开缓冲区 
			header("Cache-Control: public"); 
			Header("Content-type: application/octet-stream"); 
			Header("Accept-Ranges: bytes"); 
			if (strpos($_SERVER["HTTP_USER_AGENT"],'MSIE')) { 
			header('Content-Disposition: attachment; filename='.$paperName.'.doc'); 
			}else if (strpos($_SERVER["HTTP_USER_AGENT"],'Firefox')) { 
			Header('Content-Disposition: attachment; filename='.$paperName.'.doc'); 
			} else { 
			header('Content-Disposition: attachment; filename='.$paperName.'.doc'); 
			} 
			header("Pragma:no-cache"); 
			header("Expires:0"); 
			ob_end_flush();
						
    }
	
	/**
     * 生成试卷
     * @return mixed
     */
    public function generate()
    {
		
		$plaform_id = $this->request->param('plaform_id') ? $this->request->param('plaform_id/d') : '1';
		$id = $this->request->param('id') ? $this->request->param('id/d') : 0;
		if($plaform_id=='a' || !$id){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}

				try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AdminpaperServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AdminpaperDTO();
				$engprojectDo->plaform_id = $plaform_id;
				$engprojectDo->id = $id;
			
				$result = $api->generate($engprojectDo);
			
				if($result->code){
					$data = ['msg'=>'成功','code'=>'200','data'=>[]];
				} else {
					$data = ['msg'=>$result->message,'code'=>'400','data'=>[]];
				}

			} catch (Exception $ex) {
				$data = ['msg'=>'失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);
				
    }
	
	
	//试卷回收站列表
	public function delList(){

		$plaform_id = $this->request->param('plaform_id') ? $this->request->param('plaform_id/d') : '1';
		$page = $this->request->param('page')>1 ? $this->request->param('page/d') : 1;
		$pagesize = $this->request->param('pagesize')>0 ? $this->request->param('pagesize/d') : 10;
		$title = $this->request->param('title') ? getStr($this->request->param('title'), 'string') : '';
		$status = $this->request->param('status') ? getStr($this->request->param('status'), 'string') : '';
		
		$filename['qid'] = $this->request->param('qid') ? $this->request->param('qid/d') : 0;
		$filename['typesof'] = $this->request->param('typesof') ? $this->request->param('typesof/d') : 0;
		$filename['problemet'] = $this->request->param('problemet') ? getStr($this->request->param('problemet'), 'string') : '';//fixed 固定 randoms 随机
		$filename['shared'] = $this->request->param('shared') ? getStr($this->request->param('shared'), 'string') : '';
		$filename['plaform'] = $this->request->param('plaform') ? getStr($this->request->param('plaform'), 'string') : '';
		$filename['del'] =  1;
		if($plaform_id=='a'){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}
		
		$filename['title'] = $title;
		$filename['status'] = $status;
		$filename['page'] = $page;
		$filename['pagesize'] = $pagesize;
		$plaform_id = (int)$plaform_id;

				
				try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AdminpaperServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AdminpaperRequestDTO();
				$engprojectDo->filename = $filename;
				$result = $api->paperlist($engprojectDo);

				if($result->code){
					$res_data = empty($result->data) ? [] : $result->data;
					$data = ['msg'=>'成功','code'=>'200','data'=>$res_data,'totalNumber'=>$result->message];
				} else {
					$data = ['msg'=>'失败','code'=>'400','data'=>[],'totalNumber'=>0];
				}
			} catch (Exception $ex) {
				$data = ['msg'=>'失败','code'=>'400','data'=>[]];
			}

			return json_encode($data);

	}
	
	public function paperStatus() 
    {
		$plaform_id = $this->request->param('plaform_id') ? $this->request->param('plaform_id/d') : '1';
		$id = $this->request->param('id') ? $this->request->param('id') : 0;
		if($plaform_id=='a' || !$id){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}
		//$filename['status'] = $this->request->param('status')=='enable' ? 1 : 2;
		
		$filename['status'] = (int)$this->request->param('status');
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
           	$api = new AdminpaperServiceClient(NULL);
			\ApiClient::build($api);
			$engprojectDo = new AdminpaperRequestDTO();
            $engprojectDo->filename = $filename;
			$engprojectDo->id = $id;
			$engprojectDo->plaform_id = $plaform_id;
            $result = $api->examStatus($engprojectDo); 
			if ($result->success==true) {
               $data = ['msg'=> $result->message,'code'=>'200','data'=>[]];
            } else {
               $data = ['msg'=>$result->message,'code'=>'200','data'=>[]];
            }
		} catch (Exception $ex) {
            $data = ['msg'=>'发生异常，操作失败','code'=>'400','data'=>[]];
        }
		 return json_encode($data);
    }
	
	//共享
    public function paperShared()
    {
        $plaform_id = $this->request->param('plaform_id') ? $this->request->param('plaform_id/d') : '1';
        $id = $this->request->param('id') ? $this->request->param('id') : 0;
        if ($plaform_id == 'a' || !$id) {
            $data = ['msg' => '缺少参数', 'code' => '500'];
            return json_encode($data);
        }
        $filename['shared'] = $this->request->param('partake') == 1 ? 1 : 2;
        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk', 'gdlAgkSdk'));
            $api = new AdminpaperServiceClient(NULL);
            \ApiClient::build($api);
            $engprojectDo = new AdminpaperRequestDTO();
            $engprojectDo->filename = $filename;
            $engprojectDo->id = $id;
            $engprojectDo->plaform_id = $plaform_id;
            $result = $api->examStatus($engprojectDo);
            if ($result->code) {
                $data = ['msg' => '操作成功', 'code' => '200', 'data' => []];
            } else {
                $data = ['msg' => '操作失败', 'code' => '400', 'data' => []];
            }
        } catch (Exception $ex) {
            $data = ['msg' => '发生异常，操作失败', 'code' => '400', 'data' => []];
        }
        return json_encode($data);
    }

    public function paperDelete() 
    {
		$reg = $this->request->param('reg') ? $this->request->param('reg') : '';
		$id = $this->request->param('id') ? $this->request->param('id') : 0;
		$del = $this->request->param('del');
		if($reg=='' || !$id){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}
		if($del == 'deletes'){
			$filename['isdelete'] = 1;
		} else if($del == 'removes'){
			$filename['isdelete'] = 'removes';
		} else if($del == 'reduction'){
			$filename['isdelete'] = 0                ;
		} else {
			$data = ['msg'=>'参数错误','code'=>'500'];
			return json_encode($data);
		}
		

        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
           	$api = new AdminpaperServiceClient(NULL);
			\ApiClient::build($api);
			$engprojectDo = new AdminpaperRequestDTO();
            $engprojectDo->filename = $filename;
			$engprojectDo->id = $id;
			$engprojectDo->limit = $reg;
            $result = $api->examStatus($engprojectDo);

			if ($result->code) {
               $data = ['msg'=> $result->message,'code'=>'200','data'=>[]];
            } else {
               $data = ['msg'=>'操作失败','code'=>'200','data'=>[]];
            }
		} catch (Exception $ex) {
            $data = ['msg'=>'发生异常，操作失败','code'=>'400','data'=>[]];
        }
		 return json_encode($data);
    }
	
	//清空回收站
	public function recycleBin(){
				$reg = $this->request->param('reg') ? $this->request->param('reg') : '';
				if ($reg=='') {
					$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
					return json_encode($data);
				}
				$filename['reg'] = $reg;

				try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AdminpaperServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AdminpaperRequestDTO();
				$engprojectDo->filename = $filename;
				$result = $api->recycleBin($engprojectDo);

				if($result->code){
					$data = ['msg'=>'成功','code'=>'200','data'=>[]];
				} else {
					$data = ['msg'=>$result->message,'code'=>'400','data'=>[]];
				}
			} catch (Exception $ex) {
				$data = ['msg'=>'失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);

	}
	
	//试卷列表
	public function cloudList(){

		$plaform_id = $this->request->param('plaform_id') ? $this->request->param('plaform_id/d') : '1';
		$page = $this->request->param('page')>1 ? $this->request->param('page/d') : 1;
		$pagesize = $this->request->param('pagesize')>0 ? $this->request->param('pagesize/d') : 10;
		$title = $this->request->param('title') ? getStr($this->request->param('title'), 'string') : '';
		$status = $this->request->param('status') ? getStr($this->request->param('status'), 'string') : '';

		$filename['typesof'] = $this->request->param('typesof') ? $this->request->param('typesof/d') : 0;
		$filename['problemet'] = $this->request->param('problemet') ? getStr($this->request->param('problemet'), 'string') : '';//fixed 固定 randoms 随机

		$filename['plaform'] = $this->request->param('plaform') ? getStr($this->request->param('plaform'), 'string') : '';

		if($plaform_id=='a'){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}
		
		$filename['title'] = $title;
		$filename['status'] = $status;
		$filename['page'] = $page;
		$filename['pagesize'] = $pagesize;
		$plaform_id = (int)$plaform_id;

				
				try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AdminpaperServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AdminpaperRequestDTO();
				$engprojectDo->filename = $filename;
				$result = $api->cloudlist($engprojectDo);

				if($result->code){
					if(empty($result->data)){
						$data = ['msg'=>'成功','code'=>'200','data'=>[],'totalNumber'=>0];
					} else {
					$data = ['msg'=>'成功','code'=>'200','data'=>$result->data,'totalNumber'=>$result->message];
					}
				} else {
					$data = ['msg'=>'失败','code'=>'400','data'=>[],'totalNumber'=>0];
				}
			} catch (Exception $ex) {
				$data = ['msg'=>'失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);
	}
	
	
	//导出试卷列表
	public function cloudDown(){
		ob_end_clean();
		$filename['id'] = $this->request->param('id') ? $this->request->param('id') : '';
		$reg = $this->request->param('reg') ? $this->request->param('reg') : '';
		$page = $this->request->param('page')>1 ? $this->request->param('page/d') : 1;
		$pagesize = $this->request->param('pagesize')>0 ? $this->request->param('pagesize/d') : 10;
		$title = $this->request->param('title') ? getStr($this->request->param('title'), 'string') : '';
		$status = $this->request->param('status') ? getStr($this->request->param('status'), 'string') : '';

		$filename['typesof'] = $this->request->param('typesof') ? $this->request->param('typesof/d') : 0;
		$filename['problemet'] = $this->request->param('problemet') ? getStr($this->request->param('problemet'), 'string') : '';//fixed 固定 randoms 随机

		$filename['plaform'] = $this->request->param('plaform') ? getStr($this->request->param('plaform'), 'string') : '';

		if($reg==''){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}
		
		$filename['title'] = $title;
		$filename['status'] = $status;
		$filename['shareds'] = 1;

		

				
				try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AdminpaperServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AdminpaperRequestDTO();
				$engprojectDo->filename = $filename;
				$result = $api->cloudlist($engprojectDo);

				if($result->code){
					if(empty($result->data)){
						$index = $result->data;
					} else {
						$index = [];
					}
				} else {
					$index = [];
				}
			} catch (Exception $ex) {
				$index = [];
			}
		$filename = '云试卷列表'.date('YmdHis');  
		$header = array('ID','试卷名称','试卷来源题库','试卷类型','抽题方式','更新时间','云试卷状态','所属平台');
		if(!empty($index)){
			if($error = \Excel::exportDistance($header, $index, $filename, '2007',['F'=>['w'=>60]])) {
				throw new Exception($error);
			}
		} else {
			echo " 没有数据~~~
			<script>
				function closeWindow(){ 
					window.opener=null;
					window.close();
				}
				window.setTimeout('closeWindow()',1000);
			</script>";
			
		}
	}
	
	//添加试卷到本地
	public function addPaper() 
    {
		$plaform_id = $this->request->param('plaform_id') ? $this->request->param('plaform_id') : '1';
		$id = $this->request->param('id') ? $this->request->param('id') : 0;

		if($plaform_id=='a' || !$id){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}

        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
           	$api = new AdminpaperServiceClient(NULL);
			\ApiClient::build($api);
			$engprojectDo = new AdminpaperRequestDTO();
 
			$engprojectDo->id = $id;
			$engprojectDo->plaform_id = $plaform_id;
            $result = $api->addPaper($engprojectDo);
			if ($result->code) {
               $data = ['msg'=>'操作成功','code'=>'200','data'=>[]];
            } else {
               $data = ['msg'=>'操作失败','code'=>'200','data'=>[]];
            }
		} catch (Exception $ex) {
            $data = ['msg'=>'发生异常，操作失败','code'=>'400','data'=>[]];
        }
		 return json_encode($data);
    }
	
	//更新试卷
	public function renewPaper() 
    {
		$plaform_id = $this->request->param('plaform_id') ? $this->request->param('plaform_id/d') : '1';
		$id = $this->request->param('id') ? $this->request->param('id/d') : 0;

		if($plaform_id=='a' || !$id){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}

        try {
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
           	$api = new AdminpaperServiceClient(NULL);
			\ApiClient::build($api);
			$engprojectDo = new AdminpaperRequestDTO();
 
			$engprojectDo->id = $id;
			$engprojectDo->plaform_id = $plaform_id;
            $result = $api->renewPaper($engprojectDo);
			if ($result->code) {
               $data = ['msg'=>'操作成功','code'=>'200','data'=>[]];
            } else {
               $data = ['msg'=>'操作失败','code'=>'200','data'=>[]];
            }
		} catch (Exception $ex) {
            $data = ['msg'=>'发生异常，操作失败','code'=>'400','data'=>[]];
        }
		 return json_encode($data);
    }
	
	
	//查看试卷 测试用的
	public function lookPapers(){
		$plaform_id = $this->request->param('plaform_id') ? $this->request->param('plaform_id/d') : '1';
		$id = $this->request->param('id') ? $this->request->param('id/d') : 0;
		if($plaform_id=='a' || !$id){
			$data = ['msg'=>'缺少参数','code'=>'500'];
			return json_encode($data);
		}

				try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AdminpaperServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AdminpaperDTO();
				$engprojectDo->plaform_id = $plaform_id;
				$engprojectDo->id = $id;
				$result = $api->lookPaper($engprojectDo);

				$data = json_decode($result->message,true);

				
			} catch (Exception $ex) {
				$data = ['list'=>[],'count'=>0,'qbankName'=>'','duration'=>'','totalScore'=>'','passScore'=>'','paperName'=>''];
			}
			return json_encode($data);
			
	}
	
	//导出试卷列表
	public function downExcel(){
			ob_end_clean();
				$reg = $this->request->param('reg') ? $this->request->param('reg') : '';
				$page = $this->request->param('p')>1 ? $this->request->param('p/d') : 1;
				$pagesize = $this->request->param('num')>0 ? $this->request->param('num/d') : 10;
				$title = $this->request->param('title') ? getStr($this->request->param('title'), 'string') : '';
				$status = $this->request->param('status') ? getStr($this->request->param('status'), 'string') : '';
				
				$filename['qid'] = $this->request->param('qid') ? $this->request->param('qid/d') : 0;
				$filename['typesof'] = $this->request->param('typesof') ? $this->request->param('typesof/d') : 0;
				$filename['problemet'] = $this->request->param('problemet') ? getStr($this->request->param('problemet'), 'string') : '';//fixed 固定 randoms 随机
				$filename['shared'] = $this->request->param('shared') ? getStr($this->request->param('shared'), 'string') : '';
				$filename['plaform'] = $this->request->param('plaform') ? getStr($this->request->param('plaform'), 'string') : '';
				$filename['del'] = $this->request->param('del')=='recycling' ? 1 : 0;
				$filename['down'] = 'excels';
				$filename['id'] = $this->request->param('id') ? $this->request->param('id') : '';
				if($reg==''){
					$data = ['msg'=>'缺少参数','code'=>'500'];
					return json_encode($data);
				}
				
				$filename['title'] = $title;
				$filename['status'] = $status;
				$filename['page'] = $page;
				$filename['pagesize'] = $pagesize;
	

				
				try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AdminpaperServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AdminpaperRequestDTO();
				$engprojectDo->filename = $filename;
				$result = $api->paperlist($engprojectDo);

				if($result->code){
					if(empty($result->data)){
						$index = [];
					} else {
						$index = $result->data;
					}
				} else {
					$index = [];
				}
			} catch (Exception $ex) {
				$index = [];
			}

			
		
		$filename = '试卷列表'.date('YmdHis');  
		$header = array('排序','试卷名称','题库名称','试卷类型','抽题方式','更新时间','试卷状态','是否共享','云试卷来源','所属平台');
		if(!empty($index)){
			if($error = \Excel::exportDistance($header, $index, $filename, '2007',['F'=>['w'=>20]])) {
				throw new Exception($error);
			}
		} else {
			echo " 没有数据~~~
			<script>
				function closeWindow(){ 
					window.opener=null;
					window.close();
				}
				window.setTimeout('closeWindow()',1000);
			</script>";
			
		}
		//createtable($filename,$header,$index);  
		
	}
	
	//统计试卷数量
	public function numPapers(){
		$reg = $this->request->param('reg') ? $this->request->param('reg') : '';
		if($reg==''){
			$data = ['msg'=>'缺少参数','code'=>'500','data'=>[]];
			return json_encode($data);
		}

		try {
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
			$api = new AdminpaperServiceClient(NULL);
			\ApiClient::build($api);
			$engprojectDo = new AdminpaperDTO();
			$engprojectDo->reg = $reg;
			$result = $api->numPapers($engprojectDo);

			if($result->code){
				/**计算百分比**round*/
				$datas = $result->data[0];
				$statistic = ['total'=>$datas['totals'],'num'=>[$datas[1],$datas[2],$datas[3]],'pro'=>['1'=>0,'2'=>0,'3'=>0,]];
				unset($datas['totals']);
				foreach($datas as $k=>$v){
					//$statistic['pro'][$k] = sprintf("%.2f", ($v/$statistic['total'])*100);
					$statistic['pro'][$k] = round(($v/$statistic['total'])*100);
					
				}
				
				/**计算百分比 end***/
				$data = ['msg'=>'成功','code'=>'200','data'=>$statistic];
			
			} else {
				$data = ['msg'=>$result->message,'code'=>'400','data'=>[]];
			}

				
		} catch (Exception $ex) {
			$data = ['msg'=>'内部错误','code'=>'500','data'=>[]];
		}
		return json_encode($data);
			
	}

}
